package com.codelee.soybean;


import java.sql.*;

/**
 * transation factory
 * Created by lic on 15/6/5.
 */
public class Trans {


    /**
     * this is a transation method
     * @param conn
     * @param proccessor
     * @param engines
     */

    public static void execute(Connection conn , TransProccessor proccessor , AbstractEngine...engines){

        try {
            setAutoCommit(false,engines);
            conn.setAutoCommit(false);
            proccessor.execute(conn, engines);
            conn.commit();

        } catch (Throwable e) {

            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {

            try {

                SoybeanUtils.close(conn);
                setAutoCommit(true,engines);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

    private static void setAutoCommit(boolean autoCommit, AbstractEngine...engines){
        for(AbstractEngine engine : engines){
            engine.setAutoCommit(autoCommit);
        }
    }
}
